#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

import os
import datetime
FTPFileName='/opt/coopgis/fromgps/anonymousftproot_OtherReadOnly/incomingftpallpermissions/Locations.csv'
import shutil

#************************BEGIN Add Include Files to Path************************
import sys
NeededPaths=['/opt/coopgis/djangoproject/include', '/opt/coopgis/djangoproject']
for path in NeededPaths:
    if(not path in sys.path):
        sys.path.append(path)
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime
#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
import djangoproject
from djangoproject.models import *
#********************Setup psycopg2 and django section********************
import COOPGIS_Ajax, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
from django.template import Context, loader
from django.http import HttpResponse
from django import forms
import os
import datetime
import djangoproject.settings




def BuildJointUseEditorForm(DefaultMap, NumberOfJointUsesListedOnForm=10):
    Dict={}
    #Build Map Choices List
    MapChoices=[]
    MapChoices.append([DefaultMap.id, str(DefaultMap.Name)[:30]])
    Maps=Map.objects.all()
    for i in Maps:
        if(not i == DefaultMap):
            MapChoices.append([i.id, str(i.Name)[:30]])
    Dict['Map']=forms.ChoiceField(MapChoices, required=False)
    #Create PoleJointUseType Choices
    PoleJointUseTypeChoices=[]
    PoleJointUseTypes=PoleJointUseType.objects.all().order_by('Name')
    PoleJointUseTypeChoices.append(['-1', 'None'])
    for i in PoleJointUseTypes:
        PoleJointUseTypeChoices.append([i.id, str(i)])
    #Create PoleJointUseCompanyChoices
    PoleJointUseCompanyChoices=[]
    PoleJointUseCompanies=Company.objects.all().filter(PoleJointUseIndicator=True).order_by('Name')
    PoleJointUseCompanyChoices.append(['-1', 'None'])
    for i in PoleJointUseCompanies:
        PoleJointUseCompanyChoices.append([i.id, str(i)])
    #Create the Form Fields
    Dict['SelectGPSIndicator']=forms.BooleanField()
    Dict['SelectStationid']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectStationTagNumber']=forms.CharField(max_length = 25, required=False, widget=forms.TextInput(attrs={'size':'6'}))
    Dict['SelectSpanid']=forms.CharField(max_length = 25, required=False)
    Dict['DeleteIndicator']=forms.BooleanField()
    for i in range(0, NumberOfJointUsesListedOnForm):
        Dict['PoleJointUseType' + str(i)]=forms.ChoiceField(PoleJointUseTypeChoices, required=False)
        Dict['PoleJointUseCompany' + str(i)]=forms.ChoiceField(choices=PoleJointUseCompanyChoices, required=False)
        Dict['PoleJointUseUpdateIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['PoleJointUseDeleteIndicator' + str(i)]=forms.BooleanField(required=False)
        Dict['PoleJointUseID' + str(i)]=forms.CharField(required=False, widget=forms.TextInput(attrs={'size':'4', 'READONLY':'True'}))
    return Dict


def ProcessJointUseEditorForm(form, SelectionPole, UserName, NumberOfJointUsesListedOnForm=10):
    if(not SelectionPole):
        return
    for i in range(0, NumberOfJointUsesListedOnForm):
        try:
            PoleJointUseid=int(form.data['PoleJointUseID' + str(i)])
        except:
            PoleJointUseid='New'

        try:
            PoleJointUseTypeid=int(form.data['PoleJointUseType' + str(i)])
            poleJointUseType=PoleJointUseType.objects.filter(id__exact=PoleJointUseTypeid)[0]
        except:
            poleJointUseType=None
        try:
            PoleJointUseCompanyid=int(form.data['PoleJointUseCompany' + str(i)])
            poleJointUseCompany=Company.objects.filter(id__exact=PoleJointUseCompanyid)[0]
        except:
            poleJointUseCompany=None
        try:
            PoleJointUseUpdateIndicator=bool(form.data['PoleJointUseUpdateIndicator' + str(i)] == 'on')
        except:
            PoleJointUseUpdateIndicator=False
        try:
            PoleJointUseDeleteIndicator=bool(form.data['PoleJointUseDeleteIndicator' + str(i)] == 'on')
        except:
            PoleJointUseDeleteIndicator=False   
        if(PoleJointUseUpdateIndicator):
            if(PoleJointUseid == 'New'):  #Create a New Pole Joint Use
                CreateNewPoleJointUse(SelectionPole, poleJointUseType, poleJointUseCompany, UserName)
            elif(PoleJointUseid):  #PoleJointUse already exists, edit it [delete it and create a new pole joint use instance]
                DeletePoleJointUse(PoleJointUseid, UserName)
                CreateNewPoleJointUse(SelectionPole, poleJointUseType, poleJointUseCompany, UserName)
        elif(PoleJointUseDeleteIndicator and not PoleJointUseid == 'New'):  #Delete an Existing Pole Joint Use, ignore if referring to a new pole
            DeletePoleJointUse(PoleJointUseid, UserName)

def PopulateJointUseEditorForm(form, SelectionStation, NumberOfJointUsesListedOnForm=10):
    if(SelectionStation):
        PoleJointUses=PoleJointUse.objects.filter(Station=SelectionStation).order_by('id')
    for i in range(0, NumberOfJointUsesListedOnForm):
        try:
            form.data['PoleJointUseID' + str(i)] = str(PoleJointUses[i].id)
            form.data['PoleJointUseType' + str(i)] = str(PoleJointUses[i].PoleJointUseType.id)
            form.data['PoleJointUseCompany' + str(i)] = str(PoleJointUses[i].Company.id)
        except:
            form.data['PoleJointUseID' + str(i)] = ''
            form.data['PoleJointUseType' + str(i)] = '-1'
            form.data['PoleJointUseCompany' + str(i)] = '-1'
        form.data['PoleJointUseUpdateIndicator' + str(i)] = False
        form.data['PoleJointUseDeleteIndicator' + str(i)] = False
    return form


def CreateNewPoleJointUse(station, poleJointUseType, poleJointUseCompany, UserName):
    command=Command()
    command=command.Create(Name='CreatePoleJointUse', StartPoint=station.Point, PoleJointUseTypeName=poleJointUseType.Name, 
                           CompanyName=poleJointUseCompany.Name, CommandUserName=UserName)
    poleJointUseUpdate=command.Process()

def DeletePoleJointUse(PoleJointUseid, UserName):
    PoleJointUseToDelete=PoleJointUse.objects.filter(id=PoleJointUseid)[0]
    if(PoleJointUseToDelete.ResidesOnServerIndicator):   #Create the appropriate Command if on the server
        command=Command()
        command=command.Create(Name='DeletePoleJointUse', PoleJointUseid=PoleJointUseid, CommandUserName=UserName)
        command=command.Process()
    else:  #Delete the appropriate commands that would create it on the server if it only exists on the client
        PoleJointUseToDelete.CreateCommand.delete()
        station=PoleJointUseToDelete.Station
        PoleJointUseToDelete.delete()
        station.RebuildSymbology()
       



